#include "table_delegate.h"
#include <QPainter>
#include "table_item.h"
#include <QDebug>
#include <QStyleOptionViewItem>
#include <QRect>
#include <QMouseEvent>

TableDelegate::TableDelegate(QObject *parent):QStyledItemDelegate(parent)
{

}

void TableDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QVariant itemVar = index.data(Qt::UserRole);
    TableItem item = itemVar.value<TableItem>();

    const QList<UserInfo> users = item.users;
    int width = option.rect.width();
    const int sz = users.size();

    const int item_width = width/sz;
    QRect draw_item_rect(option.rect.x(),option.rect.y(),item_width, option.rect.height());

    painter->drawText(option.rect,Qt::AlignHCenter,item.name);

    for(int i =0;i<sz;++i)
    {
        const UserInfo &u = users[i];
        int user_left = item_width*i;

        QString item_text =QString ("位置%1:%2").arg(i+1).arg(u.name.length()==0?"无":u.name);

        painter->drawText(draw_item_rect, Qt::AlignCenter, item_text);

        draw_item_rect.translate(item_width,0);

    }

    painter->drawLine(option.rect.bottomLeft(), option.rect.bottomRight());
}


QSize TableDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{

    QVariant itemVar = index.data(Qt::UserRole);
    TableItem item = itemVar.value<TableItem>();

    return QSize(option.rect.width(), 70);
}

bool TableDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
{
    if(event->type()==QEvent::MouseButtonDblClick)
    {
        QVariant itemVar = index.data(Qt::UserRole);
        TableItem item = itemVar.value<TableItem>();

        const QList<UserInfo> users = item.users;
        int width = option.rect.width();
        const int sz = users.size();

        const double item_width = width/sz;

        QMouseEvent *m_event = static_cast< QMouseEvent *>(event);
        int p = static_cast<int>(m_event->localPos().x()/item_width);
        emit doubleClicked(index,p);
        return true;
    }
    return false;
}
